var success=queue=runningCount=createCount=vmIndex=0,start=null,countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients'),dc_config=require('../config/dc')['poc'],vmapi = new sdc.VMAPI(dc_config.vmapi),opt={},params=require('./config').params,readline = require('readline'),rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
}),os = require('os')
repl()
function repl(){
	if(params.length){
		var param=params.pop()
		rl.question('请输入'+param.id+'('+param.flag+'):\n'+(param.ex?param.ex+'\n':''), function(answer) {
			opt[param.id]=answer||param.default
			repl()
		})
	}else{
		opt.networks=[{primary: true, uuid: opt.networks}]
		console.log('配置：',opt,'\n')
		rl.question('确定要继续吗？回车继续，任意键+回车退出！！！\n', function(answer){
			if(answer)process.exit(1)
			else{
				rl.close()
				opt.quota=opt.disk
				opt.disks=[
					{image_uuid: opt.image_uuid},
					{size:opt.disk*1024}
				]
				opt.customer_metadata={root_authorized_keys:opt.root_authorized_keys}
				if(opt.vm_num>0){
					start=new Date()
					createCount=runningCount=opt.vm_num
					if(parseInt(opt.concurrent)>0&&parseInt(createCount)>parseInt(opt.concurrent)){
						queue=createCount-opt.concurrent
						createCount=opt.concurrent
						console.log('有'+queue+'台主机进入等待队列！')
					}
					serializeCreate()
				}else process.exit(1)
			}
		})
	}
}
function serializeCreate(){
	if(createCount){
		var begin=new Date()
		vmapi.createVm(opt,function(err, obj) {
			var end=new Date()
			if(err)errs(err,++vmIndex)
			else{
				console.log('\n序列化创建第'+(++vmIndex)+'项任务，api响应时间：',countdown(end,begin,countdown.ALL).toString(),
					'('+begin.getTime()+'~'+end.getTime()+')')
				var presentCount=vmIndex
				setTimeout(function(){cometState(obj,'',0,begin,presentCount)},500)
			}
			--createCount
			serializeCreate()
		})
	}
}
function createVM(){
	var begin=new Date()
	vmapi.createVm(opt,function(err, obj) {
		var end=new Date()
		if(err)errs(err,++opt.concurrent)
		else{
			console.log('\n序列化创建第'+(++opt.concurrent)+'项任务，api响应时间：',countdown(end,begin,countdown.ALL).toString(),
				'('+begin.getTime()+'~'+end.getTime()+')')
			var presentCount=opt.concurrent
			setTimeout(function(){cometState(obj,'',0,begin,presentCount)},500)
		}
	})
}
function errs(err,index){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.log('!!!!!!!!!!第'+index+'项任务无法创建',err.body.errors[e])
	else console.log('!!!!!!!!!!第'+index+'项任务无法创建',err)
}
var http = require('http');
function cometState(obj,state,i,begin,presentCount){
	var options = {
		hostname: '192.168.115.239', 
		path: '/jobs/'+obj.job_uuid,
		method: 'GET',
		headers: {"Accept": "application/json"}
	};
	var req = http.request(options, function (res) {
		var body = '';
		res.setEncoding('utf8');
		res.on('data',function(d){
			body += d;
		}).on('end', function(){
			var jobState=JSON.parse(body).execution
			if(jobState==="succeeded"||jobState==="failed"||jobState==="canceled"){
				var end=new Date()
					vmapi.getVm({uuid:obj.vm_uuid},function(err, vm){
						if(vm.state=='running'){
							++success
							console.log('\n**********第'+presentCount+'台主机创建完毕，耗时:',countdown(end,begin,countdown.ALL).toString(),'IP:',vm.nics?vm.nics[0].ip:'null','('+begin.getTime()+'~'+end.getTime()+')',jobState,vm.state,Math.abs((--runningCount)-opt.vm_num))
							if(queue){
								--queue
								createVM()
							}
						}else console.log('\n!!!!!!!!!!第'+presentCount+'台主机创建失败，耗时:',countdown(end,begin,countdown.ALL).toString(),jobState,vm.state,Math.abs((--runningCount)-opt.vm_num))
						if(!runningCount){
							console.log('\n所有'+opt.vm_num+'台主机创建完毕，成功'+success+'台，总耗时：',countdown(new Date(),start,countdown.ALL).toString(),'('+start.getTime()+'~'+new Date().getTime()+')')
							process.exit(1)
						}
					})
			}else{
				var tmo=500
				if(
					os.freemem()/os.totalmem()<=0.10||
					process.memoryUsage().heapUsed/process.memoryUsage().heapTotal>=0.90
				){
					var cpuTime=os.cpus()[0].times
					var cpuRate=(cpuTime.user+cpuTime.nice+cpuTime.irq)/(cpuTime.user+cpuTime.nice+cpuTime.irq+cpuTime.sys+cpuTime.idle)*100
					if(tmo!==1000)tmo=1000
				}if(
					os.freemem()/os.totalmem()>0.40&&
					process.memoryUsage().heapUsed/process.memoryUsage().heapTotal<0.60
				){
					if(tmo!==200)tmo=200
				}
				setTimeout(function(){cometState(obj,state,++i,begin,presentCount)},tmo)
			}
		});
	}).on('error', function(e) {		
		console.log('\n!!!!!!!!!!查询第'+presentCount+'项任务进度异常：' + e.message,Math.abs((--runningCount)-opt.vm_num));
	})
	req.end();
}